package com.fudan.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fudan.framework.entity.ResponseMsg;
import com.fudan.framework.web.controller.PathController;
import com.fudan.sys.entity.User;
import com.fudan.sys.service.UserService;

@Controller
@RequestMapping("/sys")
public class HomeController implements PathController{

	@Autowired
	private UserService userService;
	
	@Override
	public String pathPrefix() {
		return "sys";
	}
	
	@GetMapping("/login")
	public String login() {
		return "sys/login";
	}
	
	@RequestMapping("/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "sys/login";
	}
	
	@PostMapping("/login")
	@ResponseBody
	public ResponseMsg doLogin(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
				username,
				password);
		try {
			subject.login(usernamePasswordToken);
		}catch(AuthenticationException e) {
			//e.printStackTrace();
			return ResponseMsg.build(111,"用户名或密码错误");
		}
		User user = (User) subject.getPrincipal();
		HttpSession session = request.getSession(false);
		session.setAttribute("user", user);
		SavedRequest savedRequest = WebUtils.getSavedRequest(request);
		ResponseMsg responseMsg = ResponseMsg.build(600);
		if(savedRequest != null) {
			responseMsg.put("surl", savedRequest.getRequestUrl());
		}
		return responseMsg;
	}
}
